<template>
	<el-card v-loading.fullscreen.lock="loading" class="mb-20">
		<el-form :inline="true" :model="form" label-width="100" class="query_form">
			<el-row>
				<el-col :span="6">
					<el-form-item label="板块编号" prop="blockNumber">
						<el-input v-model="form.blockNumber" placeholder="请输入板块编号" clearable />
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="所属城市" prop="cityCode">
						<el-select class="m-2" placeholder="请选择城市" v-model="form.cityCode" clearable>
							<el-option v-for="item in districtTypes" :key="item.id" :value="item.areaCode"
								:label="item.areaName" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="所属区域" prop="areaCode">
						<el-select class="m-2" placeholder="请选择区域" v-model="form.areaCode" clearable>
							<el-option v-for="item in currentAreaList" :key="item.code" :value="item.code"
								:label="item.name" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="6">
					<el-form-item label="批次">
						<el-select placeholder="请选择批次" v-model="form.batchYear" clearable>
							<el-option v-for="item in batchYearList" :key="item.value" :value="item.value"
								:label="item.label" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="4" :offset="20" style="text-align: right">
					<el-button @click="resetForm">重置</el-button>
					<el-button type="primary" @click="doSearch">搜索</el-button>
				</el-col>
			</el-row>
		</el-form>
	</el-card>

	<el-card class="mb-20">
		<el-row>
			<el-button type="primary" @click="() => addRow()">+ 新建 </el-button>

			<el-button type="primary" @click="importExcel"> 批量导入 </el-button>
		</el-row>

		<vxe-grid ref="xGrid" v-bind="gridOptions" v-on="gridEvents" align="center">
			<template #index="{ rowIndex }">
				{{ (gridOptions.pagerConfig.currentPage - 1) * gridOptions.pagerConfig.pageSize + rowIndex + 1 }}
			</template>

			<template #status="{ row }">
				{{ row.status }}
			</template>

			<template #regionName="{ row }">
				{{ getRegionName(row.areaCode) }}
			</template>

			<template #categoryName="{ row }">
				{{ row.categoryName }}
			</template>

			<template #operate="{ row }">
				<ButtonItem :btns="btns" @btn-click="doAction($event, row)" />
			</template>
		</vxe-grid>
	</el-card>

	<el-dialog v-model="excelDialogVisible" title="导入" width="50%" draggable @close="closeExcelDialog">
		<div>
			<el-link mb20 type="primary" @click="downloadExcel('城市规划土拍数据导入模板.xlsx')"> 批量导入模板下载 </el-link>
		</div>

		<el-upload ref="upload" class="upload-demo" accept=".xls,.xlsx" :http-request="handleHttpRequest" :limit="1"
			:on-exceed="handleExceed" :auto-upload="false">
			<template #trigger>
				<el-button type="primary"> 选择文件 </el-button>
			</template>

			<template #tip>
				<div class="el-upload__tip text-red"> 只能上传xls,xlsx格式的Excel文件,且限制上传一个文件,新文件覆盖旧文件 </div>
			</template>
		</el-upload>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeExcelDialog">取消</el-button>

				<el-button type="primary" @click="submitUpload">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="city-plan">
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { useTable } from './hooks/city-plan-table'
import type { VxeGridInstance, VxeGridListeners } from 'vxe-table'
import ButtonItem from '@fl/components/button-item.vue'
import type { IRowV0 } from './types'
import { useRouter } from 'vue-router'
import { cloneDeep } from 'lodash-es'
import { ElMessage } from 'element-plus'
import { delLandTransaction, getRegionList, getLandTransactionList, uploadLandTransactionExcel } from '@fl/api/joint-api'
import { useAreaData } from '@/hooks/useAreaList'
const router = useRouter()
const loading = ref(false)
const dataList = ref<any>([])
const { addBtn, btns, gridOptions } = useTable()
const xGrid = ref<VxeGridInstance<IRowV0>>()
const showAdd = ref(false)
const showId = ref('')
const form = reactive({
	blockNumber: '',
	cityCode: '',
	areaCode: '',
	batchYear: ''
})
// 区域列表
const districtTypes = ref([
	{
		id: '',
		areaCode: '',
		areaName: '全部'
	}
])
const { areaList } = useAreaData()

const currentAreaList = computed(() => {
    return areaList?.value.find((item: any) => item.code === form.cityCode)?.areaList || []
})

watchEffect(() => {
	if (areaList.value) {
		form.cityCode = areaList.value[0]?.code || ''
		districtTypes.value = areaList.value.map((item: any) => ({
			id: item.code,
			areaCode: item.code,
			areaName: item.name
		}))
	}
	
})

watch(()=>form.cityCode,()=>{
    form.areaCode = ''
})

function formatTime(time) {
	if (!time) return ''
	return `${new Date(time).toJSON().substring(0, 10)} ${new Date(time).toTimeString().substring(0, 8)}`
}
const gridEvents: VxeGridListeners<IRowV0> = {
	pageChange({ currentPage, pageSize }) {
		if (gridOptions.pagerConfig) {
			gridOptions.pagerConfig.currentPage = currentPage
			gridOptions.pagerConfig.pageSize = pageSize
		}
		getData()
	}
}



const resetForm = () => {
	form.blockNumber = ''
	form.batchYear = ''
	form.areaCode = ''
	// form.cityCode = ''
	form.cityCode = areaList.value[0]?.code || ''
	doSearch()
}

async function getData(currentPage?: any, pageSize?: any) {
	if (currentPage && pageSize) {
		gridOptions.pagerConfig.currentPage = currentPage
		gridOptions.pagerConfig.pageSize = pageSize
	}
	gridOptions.loading = true
	getLandTransactionList({
		blockNumber: form.blockNumber ? form.blockNumber : undefined,
		cityCode: form.cityCode ? form.cityCode : undefined,
		areaCode: form.areaCode ? form.areaCode : undefined,
		year: form.batchYear ? form.batchYear : undefined,
		pageNum: gridOptions.pagerConfig.currentPage,
		pageSize: gridOptions.pagerConfig.pageSize
	})
		.then((res: any) => {
			if (res.code === 200) {
				const data = res.data.records ?? []
				gridOptions.loading = false
				gridOptions.pagerConfig.total = res.data.total
				gridOptions.data = data
			} else {
				ElMessage.error(res.msg)
			}
		})
		.finally(() => {
			gridOptions.loading = false
		})
}

const excelDialogVisible = ref(false)
function importExcel() {
	excelDialogVisible.value = true
}

//导入模板地址
const excelModelUrl = ref('https://public-obs-cdn.anjulian.com.cn/2025-03-05/d3a7c98a-71c1-4bf4-ad4b-5775437d8d88.xlsx')
function downloadExcel(name: string) {
	/**const fileLink = document.createElement('a')
	fileLink.href = excelModelUrl.value
	fileLink.name = name
	fileLink.setAttribute('download', '土拍导入模版（第二页有注意事项）.xlsx')
	document.body.appendChild(fileLink)
	fileLink.click()*/
	downloadFile(excelModelUrl.value, name)
}

const downloadFile = (url, filename) =>
	axios
		.get(url, {
			responseType: 'blob'
		})
		.then((res) => {
			const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据，并设置文件类型
			if (window.navigator.msSaveOrOpenBlob) {
				// 兼容IE10
				navigator.msSaveBlob(blob, filename)
			} else {
				const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
				const a = document.createElement('a')
				a.style.display = 'none'
				a.href = href // 指定下载链接
				a.download = filename // 指定下载文件名
				a.click()
				URL.revokeObjectURL(a.href) // 释放URL对象
			}
		})

const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
	upload.value!.clearFiles()
	const file = files[0] as UploadRawFile
	upload.value!.handleStart(file)
}

function submitUpload() {
	upload.value!.submit()
}

function closeExcelDialog() {
	upload.value?.clearFiles()
	excelDialogVisible.value = false
}

const loadingImport = ref(false)
function handleHttpRequest(params) {
	const file = params.file
	const fileType = file.type
	const isExcel = fileType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || fileType.includes('application/vnd.ms-excel')
	const isLt2M = file.size / 1024 / 1024 < 100
	// 这里常规检验，看项目需求而定
	if (!isExcel) {
		ElMessage.error('只能上传.xls,.xlsx格式的Excel文件!')
		return
	}
	if (!isLt2M) {
		ElMessage.error('只能上传小于100M的文件')
		return
	}
	// 根据后台需求数据格式
	const formData = new FormData()
	// 文件对象
	formData.append('file', file)
	console.log(`---${formData}`)
	// submitUpload(formData)
	uploadLandTransactionExcel(formData).then((res) => {
		console.log(res)
		if (res.code === 200) {
			excelDialogVisible.value = false
			ElMessage.success(res.msg)
			doSearch()
		} else {
			ElMessage.error(res.msg)
		}
	})
}



const batchYearList = ref<any>([])
const createBatchYearList = () => {
	// 获取当前年份
	const currentYear = new Date().getFullYear()
	// 计算5年后的年份
	const yearsBefore10 = new Array(15).fill(0).map((_, index) => currentYear - index)
	// 计算10年后的年份
	const yearsAfter10 = new Array(5).fill(0).map((_, index) => currentYear + index + 1)
	let allYear = [...yearsBefore10, ...yearsAfter10]
	const yearList = allYear.sort()
	yearList.forEach((item) => {
		batchYearList.value.push({ label: item, value: item })
	})
}

const doSearch = () => {
	gridOptions.pagerConfig.currentPage = 1
	gridOptions.pagerConfig.pageSize = 10
	getData()
}

const addRow = (id) => {
	if (id) {
		router.push('/joint/land-policy/city-plan-add?id=' + id)
	} else {
		router.push('/joint/land-policy/city-plan-add')
	}
}

async function doAction(item: any, row: any) {
	switch (item.value) {
		case 'add':
			let row1 = cloneDeep(row)
			showAdd.value = true
			showId.value = String(row.id)
			break
		case 'edit':
			addRow(row.id)
			break
		case 'view':
			let rowId = String(row.id)
			break
		case 'delete':
			delLandTransaction(String(row.id)).then((res) => {
				if (res.code === 200) {
					ElMessage.success('操作成功')
					setTimeout(() => {
						getData(1, 10)
					}, 500)
				} else {
					ElMessage.error(res.msg)
				}
			})
			getData()
			break
		default:
			break
	}
}

type areaItem = {
	areaCode: string | number
	areaName: string
}
const getRegionName = (areaCode) => {
	// console.log("🚀 ~ it ~ districtTypes:", districtTypes.value, areaCode)
	let it = districtTypes.value.find((item) => {
		return item?.areaCode == areaCode
	})

	if (it) {
		return it?.areaName
	} else {
		return ''
	}
}

onMounted(() => {
	getData()
	createBatchYearList()
})
</script>
<style lang="less" scoped>
.query_form {
	:deep(.el-form-item) {
		width: 100%;
	}

	:deep(.el-form-item__content) {
		width: 100%;
	}
}

:deep(.vxe-loading) {
	--vxe-loading-color: #da0004;
}
</style>
